<template>
  <el-form ref="form" :rules="rules" :model="form" label-width="80px">
    <el-form-item label="所属学科" prop="subjectID">
      <el-select v-model="form.subjectID" placeholder="请选择" style="width:300px">
        <el-option v-for="item in subjectsList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="目录名称" prop="directoryName">
      <el-input v-model="form.directoryName" style="width:300px" />
    </el-form-item>
    <el-form-item class="addButFn">
      <el-button @click="quitAddFormFn">取消</el-button>
      <el-button type="primary" @click="onSubmit">确认</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { simple as getSubjectsList } from '@/api/hmmm/subjects' // 获取学科列表
import { add as addDirectory, detail as getDirectoryDetail, update as updateDirectory } from '@/api/hmmm/directorys' // 获取学科列表

export default {
  name: 'DirectorysAdd',
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },
    directoryData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      form: {
        subjectID: '', // 学科id
        directoryName: '' // 目录名称
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ]

      },

      subjectsList: []
    }
  },
  created() {
    this.getSubjectsListFn()
    if (this.isEdit) {
      this.getDirectoryDetailFn()
    }
  },
  methods: {
    // 获取目录详情
    async getDirectoryDetailFn() {
      const res = await getDirectoryDetail(this.directoryData)
      this.form = res.data
    },
    // 获取学科列表
    async  getSubjectsListFn() {
      const res = await getSubjectsList()
      this.subjectsList = res.data
    },
    // 点击取消
    quitAddFormFn() {
      this.$refs.form.resetFields()
      this.$emit('closeDialog')
    },
    // 点击确定按钮，添加目录
    onSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (this.isEdit) {
          const res = updateDirectory(this.form)
          console.log(res)
          this.$message.success('修改目录成功') // 后台没有返回成功的提示
        } else {
          const res = await addDirectory(this.form)
          console.log(res)
          this.$message.success('添加目录成功') // 后台没有返回成功的提示
        }
        this.$emit('randerDirectoryList')
      })
    }
  }
}
</script>

<style scoped >
.addButFn{
  margin-top: 50px;
  margin-bottom: 10px;
   text-align: right;
}
</style>
